package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.dao.IBaseDao;
import com.sand.entity.*;
import com.sand.service.IUserInfoService;
import com.sand.util.PageModel;
import org.hibernate.criterion.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("iUserInfoService")
public class IUserInfoServiceImpl implements IUserInfoService {
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;
    /**
     * 根据用户登录名和密码查询用户信息,状态为启用（1）的用户
     *
     * @param name
     * @param pwd
     * @return
     */
    @Override
    public HashMap<String,Object> login(String name, String pwd) {
        List<HashMap<String,Object>> list = baseDao.queryObject("select new Map(" +
                "t1.rid as rid,t1.phone as phone,t1.isAttest as isAttest,t1.isHouse as isHouse,t1.createTime as createTime," +
                "t1.password as password,t2.name as name,t2.sex as sex,t2.idCard as idCard,t2.jobInfo as jobInfo," +
                "t2.avater as avater,t2.balance as balance) " +
                "from UserinfoEntity t1 inner join UserdetailsEntity t2 on t1.rid=t2.userId " +
                "where phone =?0 and password=?1 ", name, pwd);
        if(list.size()>0){
           return list.get(0);
       }else {
           return null;
       }
    }

    //根据客户id查询客户
    @Override
    public HashMap<String,Object> queryUserInfoById(int id) {
        List<HashMap<String,Object>> list = baseDao.queryObject("select new Map(" +
                "t1.phone as phone,t1.isAttest as isAttest,t1.isHouse as isHouse,t1.createTime as createTime,t2.name as name,t2.sex as sex," +
                "t2.idCard as idCard,t2.jobInfo as jobInfo,t2.avater as avater,t2.balance as balance,t3.idCardF as idCardF," +
                "t3.idCardN as idCardN) from UserinfoEntity t1 inner join UserdetailsEntity t2 on t1.rid=t2.userId inner join " +
                "UserattachmentEntity t3 on t1.rid=t3.userId where t1.rid=?0",id);
        if(list!=null && list.size()>0){
            return list.get(0);
        }
        return null;
    }

    //分页查询客户
    @Override
    public PageModel<HashMap<String,Object>> queryUserInfoLimit(int limit, int page, String condition) {
        PageModel<HashMap<String,Object>> pm = new PageModel<HashMap<String,Object>>();

        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(UserinfoEntity.class);
        //添加模糊查询条件
        if(condition!=null){
            JSONObject jsonObject = JSON.parseObject(condition);
            int con=-1;
            if(jsonObject.get("isHouse")!=null && !"".equals(jsonObject.get("isHouse"))){
                con=Integer.parseInt(jsonObject.get("isHouse").toString());
            }
            if(jsonObject.get("phone")!=null){
                dc.add(Restrictions.like("phone","%"+jsonObject.get("phone").toString()+"%"));
            }
            switch (con){
                case 0:
                    dc.add(Restrictions.eq("isHouse",0));
                    break;
                case 1:
                    dc.add(Restrictions.eq("isHouse",1));
                    break;
            }
        }

        List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
        dc.setProjection(null);
        dc.setProjection(Projections.property("rid"));
        dc.addOrder(Order.desc("rid"));
        List list = baseDao.queryObjectLimit(dc, begin, limit);
        long i=list1.get(0);
        int count= (int) i;

        List<HashMap<String,Object>> list2 = baseDao.queryObject("select new Map(t1.rid as rid,t1.phone as phone,t1.isAttest as isAttest," +
                "t1.isHouse as isHouse,t1.createTime as createTime,t1.password as password,t2.name as name) " +
                "from UserinfoEntity t1 inner join UserdetailsEntity t2 on t1.rid=t2.userId " +
                "where t1.rid in (?0)", list);

        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);
        return pm;
    }

    //根据手机号查询客户是否存在
    @Override
    public boolean queryUserInfoByPhone(String phone) {
        List<UserinfoEntity> list = baseDao.queryObject("from UserinfoEntity t where t.phone=?0", phone);
        if(list!=null){
            return true;
        }
        return false;
    }

    //根据id查询收藏记录
    @Override
    public List<HashMap<String, Object>> queryCollectionEntityById(int id) {
        List<HashMap<String, Object>> list = baseDao.queryObject("select new Map(" +
                "t3.housePicture as housePicture,t4.communityName as communityName" +
                ") from HouseattachmentEntity t3,UserinfoEntity t0 inner join CollectionEntity t1 on t0.rid=t1.userId " +
                "inner join HouseEntity t2 on t1.houseId=t2.rid " +
                "inner join CommunityEntity t4 on t2.communityId=t4.rid " +
                "where t1.houseId=t3.houseId and t3.isHouse=0 and t0.rid=?0 group by t2.rid", id);
        return list;
    }

    /**
     * 查询租客看房信息信息
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryTenantHouseViewLimit(int limit, int page, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(AppointmentformEntity.class);
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if (obj.get("userId")!=null) {
                List list = baseDao.queryObject("select t1.rid  from AppointmentformEntity t1 where t1.userId = ?0 ",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("rid", list));
            }
            criteria.add(Restrictions.eq("status",obj.get("status")));

        }

        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);

        //rid的集合
        criteria.setProjection(Projections.property("rid"));

        criteria.addOrder(Order.desc("rid"));

        //查询到所有
        List list = baseDao.queryObjectLimit(criteria, page, limit);

        long i=list1.get(0);

        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject(" select new Map(" +
                "t1.rid as rid,t1.userId as landId,t1.price as rentalPrice,t1.rentalType as rentalType," +
                "t1.houseType as houseType,t1.towards as towards," +
                "t1.renovationCondition as renovationCondition,t5.communityName as communityName," +
                "t5.communityAddress as communityAddress,t4.housePicture as housePicture," +
                "t3.browseNumber as browseNumber,t6.name as name,t7.rid as aid,t7.appointment as appointment,t7.status as appStatus)" +
                "from HouseEntity t1 inner join HouserecordEntity t3 on t3.houseId=t1.rid " +
                "inner join HouseattachmentEntity t4 on t4.houseId=t1.rid " +
                "inner join CommunityEntity t5 on t5.rid=t1.communityId " +
                "inner join CityEntity t6 on t6.rid=t5.cityId " +
                "inner join UserinfoEntity t8 on t8.rid=t1.userId " +
                "inner join AppointmentformEntity t7 on t7.houseId=t1.rid " +
                "where t4.isHouse=0 and t7.rid in (?0) group by t1.rid", list);


        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);

        return pm;
    }

    //添加收藏记录
    @Override
    public boolean addCollection(String data) {
        System.out.println(data);
        if(data!=null){
            CollectionEntity coll = JSON.parseObject(data, CollectionEntity.class);
            boolean bln = baseDao.addObject(coll);
            if(bln){
                //添加收藏量
                List<HouserecordEntity> list2 = baseDao.queryObject("select t2 from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId where t1.rid=?0", coll.getHouseId());
                HouserecordEntity houseRecord = list2.get(0);
                houseRecord.setCollectionNumber(houseRecord.getCollectionNumber()+1);
                baseDao.updateObject(houseRecord);
                return true;
            }
        }
        return false;
    }


    //添加客户
    @Override
    public boolean addUserInfo(String data) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if(data!=null){
            UserinfoEntity user = JSON.parseObject(data, UserinfoEntity.class);
            List<UserinfoEntity> list = baseDao.queryObject("from UserinfoEntity t where t.phone=?0", user.getPhone());
            if(list!=null && list.size()>0){
                return false;
            }
            //设置创建时间
            user.setCreateTime(timestamp);
            boolean bln = baseDao.addObject(user);
            if(bln){
                return true;
            }
        }
        return false;
    }

    //删除客户
    @Override
    public boolean delUserInfo(String data) {
        if(data!=null){
            //解析json数据
            List<UserinfoEntity> list = JSON.parseArray(data, UserinfoEntity.class);
            boolean bln = baseDao.delAllObject(list);
            if(bln){
                return true;
            }
        }
        return false;
    }
    //查询用户是否收藏
    @Override
    public boolean  all(int userid ,int houseId) {
        List<CollectionEntity> boo= baseDao.queryObject("from CollectionEntity where userId=?0 and houseId=?1",userid,houseId);
        if(boo.size()>0&&boo!=null){
            return true;
        }
        return false;
    }
    //删除收藏
    @Override
    public boolean ushou(String data){
        CollectionEntity coll = JSON.parseObject(data, CollectionEntity.class);
        List<CollectionEntity> boo= baseDao.queryObject("from CollectionEntity where userId=?0 and houseId=?1",coll.getUserId(),coll.getHouseId());
        for (CollectionEntity u:boo){
            System.out.println(u);
        }
        boolean b = baseDao.delObject(boo.get(0));
        return b;
    }
    //修改客户
    @Override
    public boolean updateUserInfo(String data) {
        if(data!=null){
            UserinfoEntity userInfo = JSON.parseObject(data, UserinfoEntity.class);
            boolean bln = baseDao.updateObject(userInfo);
            if(bln){
                return true;
            }
        }
        return false;
    }

    //======================lyl=====================

    //更新用户数据
    @Override
    public JSONObject updateUserData(UserinfoEntity userinfoEntity, UserdetailsEntity userdetailsEntity) {
        //设置传参对象
        JSONObject json = new JSONObject();
        //获取电话号码的用户详细
        UserinfoEntity userinfo =null;
        List templist = null;
        if(userinfoEntity.getPhone()!= null){
            templist = (List) baseDao.queryObject("from UserinfoEntity where phone=?0",userinfoEntity.getPhone());
            if(templist==null){
                return null;
            }else if(templist.size()>0){
                userinfo= (UserinfoEntity) templist.get(0);
            }
        }
        //获取身份证号码的用户详细
        UserdetailsEntity userdetails = null;
        if(userdetailsEntity.getIdCard()!=null){
            templist = (List) baseDao.queryObject("from UserdetailsEntity where idCard=?0",userdetailsEntity.getIdCard());
            if(templist!=null&&templist.size()>0){
                userdetails= (UserdetailsEntity) templist.get(0);
            }
        }

        int flag = 1;
        if(userinfo!=null){//如果电话号码有人使用且不是本人，无法修改
            if(userinfo.getRid()!=userinfoEntity.getRid()){
                return null;
            }else{
                flag=0;
            }
        }else{
            flag=0;
        }
        if(flag==0){
            if(userdetails!=null){
                if(userdetails.getRid()!=userinfoEntity.getRid()){
                    return null;
                }
            }

            if(baseDao.updateObject(userinfoEntity)){
                UserdetailsEntity userdetails1 = (UserdetailsEntity) baseDao.queryObject("from UserdetailsEntity where userId=?0",userinfoEntity.getRid()).get(0);
                userdetailsEntity.setRid(userdetails1.getRid());
                if(baseDao.updateObject(userdetailsEntity)){
                    json.put("userinfo",userinfoEntity);
                    json.put("userdetails",userdetailsEntity);
                    return json;
                }else{
                    return null;
                }
            }else{
                return null;
            }
        }
        return null;
    }

    //添加实名信息
    @Override
    public boolean addUserIdCaderImg(UserattachmentEntity userattachment) {
        boolean bln = baseDao.addObject(userattachment);
        if(bln){
            List<UserinfoEntity> list = baseDao.queryObject("from UserinfoEntity t1 where t1.rid=?0", userattachment.getUserId());
            UserinfoEntity user = list.get(0);
            user.setIsAttest(1);
            baseDao.updateObject(user);
            return true;
        }
        return false;
    }
    //查询实名信息
    @Override
    public UserattachmentEntity queryUserAchmentImg(int uid) {
        List<UserattachmentEntity> list = baseDao.queryObject("from UserattachmentEntity where userId=?0",uid);
        if(list==null&&list.size()<1){
            return null;
        }else{
            return (UserattachmentEntity) list.get(0);
        }
    }
}
